package com.example.leaderapplication.View.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.leaderapplication.Base.BaseActivity;
import com.example.leaderapplication.Base.BaseConfig;
import com.example.leaderapplication.Bean.DataBean;
import com.example.leaderapplication.Bean.IpResult;
import com.example.leaderapplication.Bean.findDocumentCatagoryAdvertisementListRequestBean;
import com.example.leaderapplication.Bean.findDocumentCatagoryAdvertisementListResultBean;
import com.example.leaderapplication.Bean.loginByLeaderRequestBean;
import com.example.leaderapplication.Bean.loginByLeaderResultBean;
import com.example.leaderapplication.R;
import com.example.leaderapplication.RetrufitHelp.BaseSubscriber;
import com.example.leaderapplication.RetrufitHelp.ExceptionHandle;
import com.example.leaderapplication.RetrufitHelp.RetrofitClient;
import com.example.leaderapplication.Utils.ListDataSave;
import com.example.leaderapplication.Utils.SPUtil;
import com.example.leaderapplication.Utils.StringUtil;
import com.example.leaderapplication.Utils.ToastUtil;
import com.example.leaderapplication.Widgets.LoadingDialog;

import java.util.List;

import okhttp3.ResponseBody;

public class LoginActivity extends BaseActivity {

    private EditText inputAccount;
    private EditText inputPassWord;

    private Button btLogin;
    private Button btRegister;

    private TextView forgetPw;

    private loginByLeaderRequestBean leaderRequestBean;
    private LoadingDialog.Builder loadBuilder;
    private LoadingDialog dialog;
    private ImageView loginBg;
    private List<DataBean> mDatas;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 动态申请权限
//        getPermissions();
    }


    @Override
    public int setLayoutId() {
        return R.layout.activity_login_jjh;
    }

    @Override
    protected void initView() {
        inputAccount = findViewById(R.id.et_account_input);
        inputPassWord = findViewById(R.id.et_password_input);
        btLogin = findViewById(R.id.bt_login);
        btRegister = findViewById(R.id.bt_regisetr);
        forgetPw = findViewById(R.id.tv_forget_pw);
        loginBg = findViewById(R.id.iv_login_bg);

        btRegister.setVisibility(View.GONE);
        forgetPw.setVisibility(View.GONE);

        //去SP 拿数据
        inputAccount.setText((String) SPUtil.get(LoginActivity.this, BaseConfig.USER_NAME, ""));
        inputPassWord.setText((String) SPUtil.get(LoginActivity.this, BaseConfig.PASS_WORD, ""));

        // 获取首页图片
        findDocumentCatagoryAdvertisementList();
    }

    private void findDocumentCatagoryAdvertisementList() {
        findDocumentCatagoryAdvertisementListRequestBean findBean = new findDocumentCatagoryAdvertisementListRequestBean();
        findBean.setAdvertisementForPagePos(2);
        findBean.setAdvertisementType(2);
        RetrofitClient.getInstance(LoginActivity.this, baseUrl).findDocumentCatagoryAdvertisementList(findBean, new BaseSubscriber<findDocumentCatagoryAdvertisementListResultBean>(LoginActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast("获取轮播图失败");
            }

            @Override
            public void onNext(findDocumentCatagoryAdvertisementListResultBean responseBody) {

                if (responseBody.getCode().equals("200")) {
                    if (responseBody.getData().size() > 0) {
                        Glide.with(LoginActivity.this)
//                            .load(responseBody.getData().get(0).getPicturePath())
                                .load(responseBody.getData().get(0).getPicturePath())
//                .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                                .into(loginBg);
                    }
                }
                // 获取轮播图成功,添加数据
//                Glide.with(LoginActivity.this)
////                            .load(responseBody.getData().get(0).getPicturePath())
//                        .load("https://img-blog.csdnimg.cn/20190220144107871.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NoZW5sYW5zMQ==,size_16,color_FFFFFF,t_70")
////                .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
//                        .into(loginBg);

            }
        });
    }
    @Override
    protected void doSomeThing() {

        //点击登入事件
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadDialog();
                gotoLogin();
            }
        });

        //点击注册事件
        btRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast("功能待开发");
            }
        });

        //点击忘记密码事件
        forgetPw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.showToast("功能待开发");
            }
        });


    }

    private void gotoLogin() {
        // 测试
//        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//        finish();
        if (StringUtil.isNullOrEmpty(inputAccount.getText().toString().trim())) {
            ToastUtil.showToast("账号为空，请输入账号");
            dimessDialog();
            return;
        }

        if (StringUtil.isNullOrEmpty(inputPassWord.getText().toString().trim())) {
            ToastUtil.showToast("密码为空，请输入密码");
            dimessDialog();
            return;
        }

        if (leaderRequestBean == null) {
            leaderRequestBean = new loginByLeaderRequestBean();
        }
        leaderRequestBean.setLoginType(3);
        leaderRequestBean.setUserName(inputAccount.getText().toString().trim());
        leaderRequestBean.setPassword(inputPassWord.getText().toString().trim());
        RetrofitClient.getInstance(LoginActivity.this, baseUrl).loginByLeader(leaderRequestBean, new BaseSubscriber<loginByLeaderResultBean>(LoginActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("登入失败" + e.message);
                        dimessDialog();
                    }
                });

            }

            @Override
            public void onNext(loginByLeaderResultBean responseBody) {

                if (responseBody.getCode().equals("200")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 先保存数据，然后再去做页面跳转
                            SPUtil.put(LoginActivity.this, BaseConfig.USER_NAME, inputAccount.getText().toString().trim());
                            SPUtil.put(LoginActivity.this, BaseConfig.PASS_WORD, inputPassWord.getText().toString().trim());
                            SPUtil.put(LoginActivity.this, BaseConfig.BUSINESS_ORG_ID, responseBody.getData().getUserInfo().getBusinessOrgId() + "");
                            SPUtil.put(LoginActivity.this, BaseConfig.ACCESS_TOKEN, responseBody.getData().getUserInfo().getAccessToken());
                            SPUtil.put(LoginActivity.this, BaseConfig.REFRESH_TOKEN, responseBody.getData().getUserInfo().getRefreshToken());

                            ListDataSave listDataSave = new ListDataSave(LoginActivity.this, BaseConfig.SP_NAME);
                            listDataSave.setDataList(BaseConfig.HOME_ITEM, responseBody.getData().getMenuList());
                            ToastUtil.showToast(responseBody.getMessage());

                            dimessDialog();
                            //  如果不为空，那么就去做网络请求
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dimessDialog();
                            ToastUtil.showToast(responseBody.getMessage());
                        }
                    });
                }
            }
        });


    }

    private void getVerificationCode() {
        RetrofitClient.getInstance(LoginActivity.this, baseUrl).getVerificationCode(new BaseSubscriber<ResponseBody>(LoginActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast("获取验证码失败");
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                ToastUtil.showToast("获取验证码成功");
            }
        });
    }

    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //表示未授权时
                //进行授权
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {

            }
        }
    }

    /**
     * 权限申请返回结果
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 申请结果数组，里面都是int类型的数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                // grantResults.length > 0&& grantResults[0] == PackageManager.PERMISSION_GRANTED
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) { //同意权限申请
                    // Toast.makeText(this,"同意权限申请",Toast.LENGTH_SHORT).show();
                    ToastUtil.showToast("同意权限申请");
                } else { //拒绝权限申请
                    //Toast.makeText(this,"权限被拒绝了",Toast.LENGTH_SHORT).show();
                    ToastUtil.showToast("权限被拒绝了");
                }
                break;
            default:
                break;
        }
    }



}
